package com.shareach.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import redis.clients.jedis.Tuple;

import com.benayn.ustyle.Dater;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import com.shareach.common.BaseQueryOrder;
import com.shareach.dao.redis.impl.DeployRDao;
import com.shareach.dao.redis.impl.DeployRDao.DeployType;
import com.shareach.domain.BaseBankDomain;
import com.shareach.domain.BaseShopDomain;
import com.shareach.domain.BizActivityDomain;
import com.shareach.domain.BizActivityShopDomain;
import com.shareach.domain.BizTicketDomain;
import com.shareach.domain.BizTuanDomain;
import com.shareach.domain.BizTuanShopDomain;
import com.shareach.service.BaseBankService;
import com.shareach.service.BaseCityService;
import com.shareach.service.BaseShopService;
import com.shareach.service.BizActivityService;
import com.shareach.service.BizActivityShopService;
import com.shareach.service.BizTicketService;
import com.shareach.service.BizTuanService;
import com.shareach.service.BizTuanShopService;

@Controller("wqueue")
@RequestMapping("/wqueue")
public class QueueErrController extends BaseController {

	@Autowired
	DeployRDao deployRDao;
	@Autowired
	BizActivityService activityService;
	@Autowired
	BizActivityShopService activityShopService;
	@Autowired
	BaseBankService bankService;
	@Autowired
	BaseShopService shopService;
	@Autowired
	BizTicketService ticketService;
	@Autowired
	BizTuanService tuanService;
	@Autowired
	BizTuanShopService tuanShopService;
	@Autowired
	private BaseCityService cityService;

	@RequestMapping(value = "/act/index.htm")
	public ModelAndView actI(final HttpServletRequest request, final Long bankId, final Integer hasdeploy) {
		// admin/queue/act/index
		return asModelAndView(DeployType.Activity, request, "admin/discount/activity/index",
				new ContentHolder<BizActivityDomain>() {
					@Override
					public Page<BizActivityDomain> getList(ModelAndView mv, List<Long> ids, BaseQueryOrder order) {

						Integer pageNo = getData(request, "pn", 1);
						Integer pageSize = getData(request, "ps", 1);
						String title = getString(request, "title", nullString, true);
						Long cityId = getData(request, "city", nullLong);
						String start = getString(request, "start", nullString, true);
						if (pageNo < 1)
							pageNo = 1;
						if (pageSize <= 1) {
							pageSize = defaultPageSize;
						}
						BizActivityDomain query = new BizActivityDomain();
						query.setCity(cityId);
						query.setTitle(title);
						addCriteria(query, hasdeploy, "deployTime");

						List<BaseBankDomain> banks = bankService.findAll();

						mv.addObject("conditions", ImmutableMap.of("bankId", null == bankId ? -1 : bankId));
						mv.addObject("banks", banks);
						mv.addObject("title", title);
						mv.addObject("cityId", cityId);
						mv.addObject("deploy", hasdeploy);
						mv.addObject("start", start);

						if (ids != null && ids.size() > 0) {
							query.setInOpreatorSet(ids);
						} else {
							return null;
						}

						order.setNumber(pageNo.toString());
						order.setPageSize(pageSize);
						Page<BizActivityDomain> result = activityService.getPageResult(query, order);
						return result;
					}
				});
	}

	@RequestMapping(value = "/actsh/index.htm")
	public ModelAndView actshI(final HttpServletRequest request, final String name, final Long cityId,
			final String title, final Integer hasmatch) {
		// admin/queue/actsh/index
		return asModelAndView(DeployType.ActivityShop, request, "admin/discount/activity/activityShopes",
				new ContentHolder<BizActivityShopDomain>() {
					@Override
					public Page<BizActivityShopDomain> getList(ModelAndView mv, List<Long> ids, BaseQueryOrder order) {
						BizActivityShopDomain domain = new BizActivityShopDomain();
						order.setNumber(getPageNo(request).toString());
						order.setPageSize(getPageSize(request));
						order.addSort("_id", Order.DESCENDING.toString());

						addCriteria(domain, hasmatch, "shopId");
						mv.addObject("match", hasmatch);

						if (StringUtils.isNotEmpty(title)) {
							domain.addRegexMap(title, "title");
							mv.addObject("title", title);
						}
						if (StringUtils.isNotEmpty(name)) {
							String _name = name.trim();
							domain.addRegexMap(_name, new String[] { "name", "brandName", "orgName" });
							mv.addObject("name", _name);
						}
						if (cityId != null) {
							domain.setCity(cityId);
							mv.addObject("cityId", cityId);
						}
						if (ids != null && ids.size() > 0) {
							domain.setInOpreatorSet(ids);
						} else {
							return null;
						}
						Page<BizActivityShopDomain> activityShopList = activityShopService.getPageResult(domain, order);
						for (BizActivityShopDomain activitydom : activityShopList.getContent()) {
							Long shopId = activitydom.getShopId();
							if (shopId != null) {
								activitydom.setBaseShop(shopService.getById(shopId));
							}
						}
						return activityShopList;
					}
				});
	}

	@RequestMapping(value = "/bank/index.htm")
	public ModelAndView bankI(final HttpServletRequest request) {
		// admin/queue/bank/index
		return asModelAndView(DeployType.Bank, request, "admin/dic/bank/index", new ContentHolder<BaseBankDomain>() {
			@Override
			public Page<BaseBankDomain> getList(ModelAndView mv, List<Long> ids, BaseQueryOrder order) {
				order.setNumber(getPageNo(request).toString());
				order.setPageSize(getPageSize(request));
				order.addSort("_id", Order.DESCENDING.toString());
				BaseBankDomain domain = new BaseBankDomain();
				if (ids != null && ids.size() > 0) {
					domain.setInOpreatorSet(ids);
				} else {
					return null;
				}
				Page<BaseBankDomain> banks = bankService.getPageResult(domain, order);
				return banks;
			}
		});
	}

	@RequestMapping(value = "/shop/index.htm")
	public ModelAndView shopI(final HttpServletRequest request, final Integer hasdeploy, final Integer hasimg,
			final Integer hastel, final Integer hasweibo, final Integer hasaddr, final Integer hasloc,
			final Integer hasprice, Long id, final String brand, final String name) {
		// admin/queue/shop/index
		return asModelAndView(DeployType.Shop, request, "admin/shop/shop/index", new ContentHolder<BaseShopDomain>() {
			@Override
			public Page<BaseShopDomain> getList(ModelAndView mv, List<Long> ids, BaseQueryOrder order) {

				order.setNumber(getPageNo(request).toString());
				order.setPageSize(getPageSize(request));
				order.addSort("_id", Order.DESCENDING.toString());

				BaseShopDomain domain = new BaseShopDomain();
				addCriteria(domain, hasdeploy, "deployTime");
				addCriteria(domain, hastel, "tels");
				addCriteria(domain, hasimg, "img");
				addCriteria(domain, hasweibo, "weiboId");
				addCriteria(domain, hasaddr, "addr");
				addCriteria(domain, hasloc, "loc");
				addCriteria(domain, hasprice, "price");
				Map<String, Integer> conditions = new HashMap<String, Integer>();
				conditions.put("deploy", null == hasdeploy ? 1 : hasdeploy);
				conditions.put("img", null == hasimg ? 1 : hasimg);
				conditions.put("tels", null == hastel ? 1 : hastel);
				conditions.put("weiboId", null == hasweibo ? 1 : hasweibo);
				conditions.put("addr", null == hasaddr ? 1 : hasaddr);
				conditions.put("loc", null == hasloc ? 1 : hasloc);
				conditions.put("price", null == hasprice ? 1 : hasprice);
				mv.addObject("conditions", conditions);
				if (StringUtils.isNotEmpty(brand)) {
					domain.setBrand(brand);
					mv.addObject("brand", brand);
				}
				if (StringUtils.isNotEmpty(name)) {
					domain.addRegexMap(name.trim(), "name");
				}
				if (ids != null && ids.size() > 0) {
					domain.setInOpreatorSet(ids);
				} else {
					return null;
				}

				Page<BaseShopDomain> shops = shopService.getPageResult(domain, order);

				return shops;
			}
		});
	}

	@RequestMapping(value = "/ticket/index.htm")
	public ModelAndView ticketI(final HttpServletRequest request, final String name, final Long cityId,
			final String title, final Integer hasmatch) {
		// admin/queue/ticket/index
		return asModelAndView(DeployType.Ticket, request, "admin/discount/ticket/index",
				new ContentHolder<BizTicketDomain>() {
					@Override
					public Page<BizTicketDomain> getList(ModelAndView mv, List<Long> ids, BaseQueryOrder order) {
						BizTicketDomain domain = new BizTicketDomain();
						order.setNumber(getPageNo(request).toString());
						order.setPageSize(getPageSize(request));
						order.addSort("_id", Order.DESCENDING.toString());

						addCriteria(domain, hasmatch, "shopId");
						mv.addObject("match", hasmatch);

						if (StringUtils.isNotEmpty(title)) {
							domain.addRegexMap(title, "title");
							mv.addObject("title", title);
						}
						if (StringUtils.isNotEmpty(name)) {
							String _name = name.trim();
							domain.addRegexMap(_name, new String[] { "name", "brandName", "orgName" });
							mv.addObject("name", _name);
						}
						if (cityId != null) {
							domain.setCity(cityId);
							mv.addObject("cityId", cityId);
						}
						if (ids != null && ids.size() > 0) {
							domain.setInOpreatorSet(ids);
						} else {
							return null;
						}
						Page<BizTicketDomain> ticketList = ticketService.getPageResult(domain, order);
						for (BizTicketDomain ticketdom : ticketList.getContent()) {
							Long shopId = ticketdom.getShopId();
							if (shopId != null) {
								ticketdom.setBaseShop(shopService.getById(shopId));
							}
						}
						return ticketList;
					}
				});
	}

	@RequestMapping(value = "/tuan/index.htm")
	public ModelAndView tuanI(final HttpServletRequest request, final Long cityId, final String title) {
		// admin/queue/tuan/index
		return asModelAndView(DeployType.Tuan, request, "admin/discount/tuan/index",
				new ContentHolder<BizTuanDomain>() {
					@Override
					public Page<BizTuanDomain> getList(ModelAndView mv, List<Long> ids, BaseQueryOrder order) {

						BizTuanDomain domain = new BizTuanDomain();

						order.setNumber(getPageNo(request).toString());
						order.setPageSize(getPageSize(request));
						order.addSort("_id", Order.DESCENDING.toString());

						Map<String, Object> conditions = Maps.newHashMap();
						if (null != cityId) {
							conditions.put("cityId", cityId);
							domain.setCity(cityId);
						}
						if (StringUtils.isNotEmpty(title)) {
							domain.addRegexMap(title.trim(), "title");
							conditions.put("title", title);
						}
						mv.addObject("conditions", conditions);
						if (ids != null && ids.size() > 0) {
							domain.setInOpreatorSet(ids);
						} else {
							return null;
						}
						Page<BizTuanDomain> tuans = tuanService.getPageResult(domain, order);

						return tuans;
					}
				});
	}

	@RequestMapping(value = "/tuansh/index.htm")
	public ModelAndView tuanshI(final HttpServletRequest request, final Long cityId, final String name,
			final Integer hasmatch) {
		// String s="admin/queue/tuansh/index";
		return asModelAndView(DeployType.TuanShop, request, "admin/discount/tuan/shop/index",
				new ContentHolder<BizTuanShopDomain>() {

					@Override
					public Page<BizTuanShopDomain> getList(ModelAndView mv, List<Long> ids, BaseQueryOrder order) {
						BizTuanShopDomain domain = new BizTuanShopDomain();

						order.setNumber(getPageNo(request).toString());
						order.setPageSize(getPageSize(request));
						order.addSort("_id", Order.DESCENDING.toString());

						if (StringUtils.isNotEmpty(name)) {
							domain.addRegexMap(name, new String[] { "name", "brandName", "orgName" });
							mv.addObject("name", name);
						}
						if (null != cityId) {
							domain.setCity(cityId);
							mv.addObject("cityId", cityId);
						}
						if (ids != null && ids.size() > 0) {
							domain.setInOpreatorSet(ids);
						} else {
							return null;
						}
						addCriteria(domain, hasmatch, "shopId");
						mv.addObject("match", hasmatch);
						Page<BizTuanShopDomain> tuanShopPage = tuanShopService.getPageResult(domain, order);
						// List<BizTuanShopDomain> tuanShopList =
						// tuanShopService.getListByIds(domain, ids, order);
						for (BizTuanShopDomain tuanShop : tuanShopPage.getContent()) {
							Long shopId = tuanShop.getShopId();
							if (shopId != null) {
								tuanShop.setBaseShop(shopService.getById(shopId));
							}
						}
						return tuanShopPage;
					}
				});
	}

	interface ContentHolder<E> {
		Page<E> getList(ModelAndView mv, List<Long> ids, BaseQueryOrder order);
	}

	private <E> ModelAndView asModelAndView(DeployType type, HttpServletRequest request, String returnPage,
			ContentHolder<E> holder) {
		ModelAndView mv = new ModelAndView(returnPage);
		Set<Tuple> tuples = deployRDao.getErrDeployList(type, 1, (int) deployRDao.getErrDeployListSize(type));
		List<Long> ids = Lists.newArrayList();
		Map<String, String> errTimes = Maps.newHashMap();
		for (Tuple tuple : tuples) {
			ids.add(Longs.tryParse(tuple.getElement()));
			errTimes.put(tuple.getElement(), Dater.of(((Double) tuple.getScore()).longValue()).asText());
		}

		BaseQueryOrder order = new BaseQueryOrder();
		Page<E> resultPage = holder.getList(mv, ids, order);
		mv.addObject("result", resultPage);
		mv.addObject("errTimes", errTimes);
		mv.addObject("flag", "error");
		mv.addObject("cities", cityService.findAll());
		return mv;
	}

}
